package com.goldman.aplt.base.interceptor;

import com.goldman.aplt.base.exception.BankBusiException;
import com.goldman.aplt.base.type.BaseEnumType;
import com.goldman.aplt.base.type.BusiResponseData;
import com.goldman.aplt.base.type.CmErrorCode;
import com.goldman.aplt.entity.AppErrorMapping;
import com.goldman.aplt.service.AppErrorMappingService;
import com.goldman.base.common.sys.exception.BusinessException;
import com.goldman.base.common.sys.interceptor.ExceptionInterceptor;
import com.goldman.http.common.s2s.model.ErrorCode;
import com.goldman.http.common.s2s.model.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.text.MessageFormat;

@Slf4j
@Order(1)
@RestControllerAdvice
public class ApltExceptionInterceptor extends ExceptionInterceptor {

    public static final String DEFAULT_ERROR_MSG = "System error[ERRORCODE], please contact customer service";
    @Resource
    private AppErrorMappingService appErrorMappingService;

    @ExceptionHandler(BankBusiException.class)
    public BusiResponseData hanldeBusiExcetpion(BankBusiException ex) {
        log.error("business exception", ex);

        String errMsg = ex.getMsg();
        //核心错误映射已经在coreutil处理
        if(ex.getCode().equals(CmErrorCode.CORE_SYS_ERROR.getCode())) {
            return BusiResponseData.newWhenErr(ex.getCode(), errMsg, ex.getError());
        }

        AppErrorMapping errorMapping = appErrorMappingService.selOne(ex.getCode(), BaseEnumType.E_LANGUAGE.ENGLISH.getValue());
        if(errorMapping != null) {
            errMsg = errorMapping.getMessage();
            if(ex.getArgs() != null && ex.getArgs().length > 0) {
                errMsg = MessageFormat.format(errMsg, ex.getArgs());
            }
        } else {
            errMsg = DEFAULT_ERROR_MSG.replace("ERRORCODE", ex.getCode());
        }

        return BusiResponseData.newWhenErr(ex.getCode(), errMsg, ex.getError());
    }

    @Override
    @ExceptionHandler(BusinessException.class)
    public ResponseData hanldeBusinessExcetpion(BusinessException ex) {
        log.error("business exception", ex);
        return ResponseData.newWhenErr(ex.getCode(), DEFAULT_ERROR_MSG.replace("ERRORCODE", ex.getCode().toString()), ex.getError());
    }

    @Override
    @ExceptionHandler(Throwable.class)
    public ResponseData handleError(Throwable ex) {
        log.error("system exception", ex);
        return ResponseData.newWhenErr(ErrorCode.SYS_ERROR.getCode(), DEFAULT_ERROR_MSG.replace("ERRORCODE", ErrorCode.SYS_ERROR.getCode().toString()), ex.getMessage());
    }
}
